package com.example.geo_quiz;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class CheatActivity extends Activity {
	
	private TextView lbAnswer;
	private Button btnShowAnswer;
	
	private boolean mAnswerIsTrue;
	private boolean mIsAnswerShown;
	
	private static final String TAG = "CheatActivity";
	public static final String EXTRA_ANSWER_IS_TRUE = "com.example.geo_quiz.answer_is_true";
	public static final String EXTRA_ANSWER_SHOWN = "com.example.geo_quiz.answer_shown";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_cheat);
		
		//init controls
		lbAnswer = (TextView) findViewById(R.id.lbAnswer);
		btnShowAnswer = (Button) findViewById(R.id.btnShowAnswer);
		
		// get extra value from MainActivity
		mAnswerIsTrue = getIntent().getBooleanExtra(EXTRA_ANSWER_IS_TRUE, false);
		
		// get current mIsAnswerShown saved in onSavedInstanceState
		if (savedInstanceState != null) {
			mIsAnswerShown = savedInstanceState.getBoolean(EXTRA_ANSWER_SHOWN);
		} else { //if no saved mIsAnswerShown 
			// Answer Shown will not be true until user presses the button 'Show Answer'
			mIsAnswerShown = false;
			setAnswerShownResult(mIsAnswerShown);
		}
		
		// show the answer in textview
		btnShowAnswer.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (mAnswerIsTrue) {
					lbAnswer.setText(R.string.true_button);
				} else {
					lbAnswer.setText(R.string.false_button);
				}
				mIsAnswerShown = true;
				setAnswerShownResult(mIsAnswerShown);
			}
		});
		
	}

	protected void setAnswerShownResult(boolean isAnswerShown) {
		Intent data = new Intent();
		data.putExtra(EXTRA_ANSWER_SHOWN, isAnswerShown);
		setResult(RESULT_OK, data);
	}
	
	/**
	 * maintain the mIsAnswerShown when user rotates the device to prevent cheater
	 * Chapter 5 challenges
	 */
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		
		Log.i(TAG, "onSaveInstanceState");
		outState.putBoolean(EXTRA_ANSWER_SHOWN, mIsAnswerShown);
	}
}
